package androidserver.control;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import androidserver.exceptions.MyJSONException;
import androidserver.jsonprocessor.json.JSONException;
import androidserver.jsonprocessor.json.JSONObject;
import androidserver.matlabprocessor.matlabclient.MatlabImageProcessor;

public class Control { //TODO new classes for specific stuff
	private static Control INSTANCE = null;
	private static final String baseDir = "/home/aron/workspace/andrOCR_server_servlet/uploads/";// TODO
																									// from
																									// config

	private Control() {
	}

	public static Control getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new Control();
		}
		return INSTANCE;
	}

	public String processMatlabRequest(String command, int returnCount) throws MyJSONException {
		MatlabImageProcessor matlabProc = new MatlabImageProcessor();
		String recognizedText = matlabProc.processMatlabRequest(command, returnCount);

		return recognizedText;
	}

	public String convertAndSaveImageToDisk(String imgString) throws MyJSONException { // TODO: new
																// class for
																// save
		try {
			byte[] buf = new sun.misc.BASE64Decoder().decodeBuffer(imgString);
			String filePath = baseDir + "mypic.jpg"; //TODO: random name
			FileOutputStream fos = new FileOutputStream(filePath);
			fos.write(buf);
			fos.close();
			return filePath;
		} catch (IOException e) {
			throw new MyJSONException(MyJSONException.IO_ERROR);
		}
	}

	public JSONObject processRequest(JSONObject jsonRequest) throws MyJSONException {
		String imgString = null;
		try {
			imgString = jsonRequest.getString("img");
		} catch (JSONException e) {
			e.printStackTrace();
			throw new MyJSONException(MyJSONException.IMG_ERROR);
		}
		
		
		String imagePath = convertAndSaveImageToDisk(imgString);
		
		String matlabReturnedText = processMatlabRequest(
				"main('" + imagePath + "')", 1);
		
		try {
			JSONObject jsonResponse = new JSONObject();
			jsonResponse.put("recText", matlabReturnedText);
			return jsonResponse;
		} catch (JSONException e) {
			throw new MyJSONException(MyJSONException.PUT_ERROR);
		}
	}
}
